﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading.Tasks;
using System.Configuration;
using Simple.Data.SqlServer;
using Simple.Data.Ado;
using Simple.Data;
using Nop.Core;
using Nop.Core.Domain.Directory;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace CurrencyUpdateTimer
{
    class Program
    {
        static void Main(string[] args)
        {
            if (!UpdateAllCurrency(GetAllCurrency()))
            {
                throw new Exception("Error");
            }
        }
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";  
        public static string DbConnectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString.ToString();
        public static string DataSourceURL = ConfigurationManager.ConnectionStrings["DataSourceURL"].ConnectionString.ToString();
        protected static dynamic db = Database.OpenConnection(DbConnectionString);
        public static IEnumerable<Currency> GetAllCurrency()
        {
            return db.Currency.All();
        }
        public static bool UpdateAllCurrency(IEnumerable<Currency> currencies)
        {
            if (currencies != null && currencies.Count() > 0)
            {
                try
                {
                    foreach(var currency in currencies)
                    {
                        if (currency.CountryCode.Trim() == "CA")
                        {
                            continue;
                        }
                        currency.Rate = GetRate("CAD",currency.CurrencyCode);
                        db.Currency.UpdateById(currency);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return false;
        }
        /// <summary>
        /// countryCodeBe = countryCodeBase * Rate
        /// </summary>
        /// <param name="countryCodeBe"></param>
        /// <param name="contryCodeEnd"></param>
        /// <returns></returns>
        public static decimal GetRate(string currencyCodeFrom, string currencyCodeTo)
        {
            string url = "http://www.xe.com/zh-CN/currencyconverter/convert/?Amount=1&From={0}&To={1}";
            url = string.Format(url, currencyCodeFrom, currencyCodeTo);
            string tempA = "<td width=\"47%\" align=\"left\" class=\"rightCol\">";
            string tempB = "&nbsp;<span class=\"uccResCde\">"+currencyCodeTo+"</span>";
            string result = SendRequest(true, 5000, url, DefaultUserAgent, tempA, tempB);
            decimal rate = 0.0M;
            Decimal.TryParse(result, out rate);
            return rate;
        }
        public static string SendRequest(bool isGet, int? timeOut, string url, string userAgent, string tempRegStart, string tempRegEnd, CookieCollection cookies = null)
        {
            if (isGet)
            {
                if (!string.IsNullOrEmpty(url))
                {
                    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                    request.Method = "GET";
                    request.UserAgent = userAgent;
                    if (timeOut.HasValue)
                    {
                        request.Timeout = timeOut.Value;
                    }
                    if (cookies != null)
                    {
                        request.CookieContainer = new CookieContainer();
                        request.CookieContainer.Add(cookies);
                    }
                    Stream htmlStram = request.GetResponse().GetResponseStream();
                    StreamReader reader = new StreamReader(htmlStram);
                    string result = reader.ReadToEnd();
                    reader.Close();
                    Regex reg = new Regex(tempRegStart + "(.*)" + tempRegEnd);
                    string test = reg.Match(result).Value;
                    test = test.Replace(tempRegStart, "");
                    test = test.Replace(tempRegEnd, "");
                    return test;
                }
            }
            return "";
        }
    }
}
